import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {

    public static void saveImage(String url, String savePath) throws IOException {
        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }


    public static void ensureDirectoryExists(String dirPath) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    public static void appendLog(String url, String savePath) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = sdf.format(new Date());
        String log = String.format("%s Downloaded: %s -> %s%n", time, url, savePath);

        try (FileWriter fw = new FileWriter("download_log.txt", true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(log);
        } catch (IOException e) {
            System.out.println("记录日志时发生错误: " + e.getMessage());
        }
    }
}
